<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form :form="form">
                    <a-form-item style="display:none">
                        <a-input v-decorator="['id']"/>
                        <a-input v-decorator="['boId']"/>
                        <a-input v-decorator="['boName']"/>
                    </a-form-item>
                    <a-row>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol"
                                         :label="i18n('form.templateName','模板名称')">
                                <a-input :placeholder="i18n('form.templateName','模板名称')"
                                         v-decorator="['name', {rules: [{required: true, message: '请输入模板名称'}]}]"/>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.alias','别名')">
                                <a-input :placeholder="i18n('form.alias','别名')"
                                         v-decorator="['alias', {rules: [{required: true, message: '请输入别名'}]}]"/>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="24">
                            <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                         :label="i18n('form.bgImage','背景图')">
                                <a-upload
                                    name="files"
                                    listType="picture-card"
                                    class="avatar-uploader"
                                    :showUploadList="false"
                                    action="/api/api-system/system/core/sysFile/upload"
                                    :headers="headers"
                                    :beforeUpload="beforeUpload"
                                    @change="handleChange"
                                >
                                    <img v-if="imageUrl" :src="imageUrl" alt="photo"/>
                                    <div v-else>
                                        <a-icon :type="loading ? 'loading' : 'plus'"/>
                                        <div class="ant-upload-text">{{ $ti18('rxList.upload', '上传') }}</div>
                                    </div>
                                </a-upload>
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row>
                        <a-col :span="24">
                            <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1"
                                         :label="i18n('list.printTemplate','套打模板')">
                                <a-button @click="design">
                                    {{ i18n('list.design', '设计') }}
                                </a-button>
                                <a-button style="margin-left: 8px" @click="showFormFieldDlg">
                                    {{ i18n('list.addFromForm', '从表单中添加') }}
                                </a-button>
                                <a-select :placeholder="i18n('list.approveData','审批相关数据')" @change="approveChange"
                                          allowClear style="display: inline-block;width: 30%;">
                                    <a-select-option value="history">
                                        {{ i18n('list.history', '审批历史') }}
                                    </a-select-option>
                                    <a-select-option value="opinion">
                                        {{ i18n('list.opinion', '审批意见') }}
                                    </a-select-option>
                                    <a-select-option value="curUserId">
                                        {{ i18n('list.curUserId', '当前人ID') }}
                                    </a-select-option>
                                    <a-select-option value="curUserName">
                                        {{ i18n('list.curUserName', '当前人名称') }}
                                    </a-select-option>
                                    <a-select-option v-for="vars in varsOptions" :key="vars.value" :value="vars.value">
                                        {{ vars.label }}
                                    </a-select-option>
                                </a-select>
                                <rx-monaco-editor
                                    ref="scriptCode"
                                    v-model="template"
                                    language="javascript"
                                    style="height:300px;"
                                >
                                </rx-monaco-editor>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </rx-layout>

    </rx-dialog>
</template>
<script>
import FormPrintLodopApi from '@/api/form/core/formPrintLodop'
import {BaseForm, RxDialog, Util, RxMonacoEditor,TokenUtil} from "@lowcode/jpaas-common-lib";
import FormBoAttrApi from "@/api/form/bo/formBoAttr";
import BpmPublicApi from "@/api/bpm/core/BpmPublicApi";

export default {
    name: 'FormPrintLodopEdit',
    mixins: [BaseForm],
    props: ["boId", "boName", "boDefId"],
    components: {
        RxDialog,
        RxMonacoEditor
    },
    data() {
        return {
            imageUrl: "",
            loading: false,
            headers: {},
            backImg: "",
            template: "",
            varsOptions: [],
            lodopUtil: {},
            fileList: []
        }
    },
    computed: {
        scriptCode() {
            return this.$refs.scriptCode;
        }
    },
    created() {
        this.loadVars();
        this.initUpload();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "printLodop", key);
        },
        loadVars() {
            var self = this;
            BpmPublicApi.getVariables().then(res => {
                var tmp = [];
                //全局变量
                tmp.push(...res);
                tmp.forEach(function (el, index) {
                    self.varsOptions.push({label: el.label, value: el.key})
                });
            })
        },
        initUpload() {
            var token = TokenUtil.getToken();
            if (token) {
                this.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
            }
        },
        onload_(values) {
            if (!values) {
                this.mdl = {boId: this.boId, boName: this.boName};
                this.form.setFieldsValue(this.mdl);
            } else {
                if (values.backImg) {
                    this.backImg = values.backImg;
                    this.imageUrl = this.getFilePath(values.backImg, true);
                }
                this.template = values.template;
            }
        },
        get(id) {
            return FormPrintLodopApi.get(id);
        },
        save(values) {
            values.template = this.template;
            values.backImg = this.backImg;
            return FormPrintLodopApi.save(values);
        },
        design() {
            var files = require.context('@/utils', true, /\.js$/);
            files.keys().forEach(key => {
                if (key.indexOf('/LodopFuncs.js') != -1) {
                    this.lodopUtil = files(key).default || files(key)
                }
            })
            var self = this;
            this.lodopUtil.onload(function (LODOP) {
                if (!LODOP) {
                    return;
                }
                var name = self.form.getFieldValue("name");
                //初始化任务名称
                LODOP.PRINT_INIT(name);
                if (self.backImg) {
                    //设置背景图
                    LODOP.ADD_PRINT_SETUP_BKIMG("<img src='" + self.getFilePath(self.backImg, false) + "' />");
                    //设置打印显示
                    LODOP.SET_SHOW_MODE("BKIMG_PRINT", true);
                }
                self.initPrint();
            })
        },
        initPrint() {
            var self = this;
            eval(this.template);
            if (LODOP.CVERSION) {
                CLODOP.On_Return = function (TaskID, Value) {
                    self.template = Value;
                };
            }
            //打印设计
            LODOP.PRINT_DESIGN();
        },
        showFormFieldDlg() {
            var self_ = this;
            var config = {
                curVm: self_, widthHeight: ['800px', '600px']
            };
            if (!this.boDefId) {
                this.$confirm({
                    title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                    content: this.i18n('list.boModelNullMsg', '业务模型为空'),
                    cancelText: this.$ti18('rxForm.cancelBtn', '警告')
                });
                return;
            }
            Object.assign(config, {
                data: {
                    boDefId: this.boDefId
                }
            });
            FormBoAttrApi.openBoAttrDialog(config, function (data) {
                if (data.type == 'main') {
                    for (var i = 0; i < data.returnArray.length; i++) {
                        var field = data.returnArray[i];
                        var fieldName = field.field;
                        if (field.isSingle == 0) {
                            fieldName += ".label";
                        }
                        var f = "LODOP.ADD_PRINT_TEXT(0,0,278,24,\"${" + fieldName + "}\");\n";
                        self_.scriptCode.insertContent(f);
                    }
                } else if (data.type == 'onetomany') {
                    var headers = "<tr>";
                    var fields = "<#list sub__" + data.entName + " as obj><tr>";
                    for (var i = 0; i < data.returnArray.length; i++) {
                        var field = data.returnArray[i];
                        headers += "<td>" + field.label + "</td>";
                        var fieldName = field.field;
                        if (field.isSingle == 0) {
                            fieldName += ".label";
                        }
                        fields += "<td>${obj." + fieldName + "}</td>";
                    }
                    headers += "<tr>";
                    fields += "</tr></#list>";
                    var f = "LODOP.ADD_PRINT_TABLE(0,0,300,100,\"<style> table,td,th {border: 1px solid black;border-style: solid;border-collapse: collapse}</style><table border='1'>" + headers + fields + "</table>\");\n";
                    self_.scriptCode.insertContent(f);
                } else if (data.type == 'onetoone') {
                    for (var i = 0; i < data.returnArray.length; i++) {
                        var field = data.returnArray[i];
                        var fieldName = field.field;
                        if (field.isSingle == 0) {
                            fieldName += ".label";
                        }
                        var f = "LODOP.ADD_PRINT_TEXT(0,0,278,24,\"${sub__" + data.entName + "." + fieldName + "}\");\n";
                        self_.scriptCode.insertContent(f);
                    }
                }
            });
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                this.$message.error('You can only upload JPG or PNG file!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$message.error('Image must smaller than 2MB!');
            }
            return isJpgOrPng && isLt2M;
        },
        getFilePath(fileId, isScale) {
            fileId = Util.encryptWord(fileId);
            isScale = Util.encryptWord(isScale);
            let token = TokenUtil.getToken();
            return "/api/api-system/system/core/sysFile/previewImg?fileId=" + fileId + "&accessToken=" + token + "&isScale=" + isScale;
        },
        handleChange(info) {
            if (info.file.status === 'uploading') {
                this.loading = true;
                return;
            }
            if (info.file.status === 'done') {
                var res = info.file.response;
                if (res.success) {
                    this.backImg = res.data[0].fileId;
                    this.imageUrl = this.getFilePath(res.data[0].fileId, true);
                    this.loading = false;
                }
            }
        },
        approveChange(value) {
            var self_ = this;
            var f = '';
            if (value == 'history') {
                var objAry = [
                    {label: this.i18n('hisHtml.sendTime', '发送时间'), field: 'createTime'},
                    {label: this.i18n('hisHtml.completeTime', '处理时间'), field: 'completeTime'},
                    {label: this.i18n('hisHtml.duration', '停留时间'), field: 'duration'},
                    {label: this.i18n('hisHtml.nodeName', '审批节点'), field: 'nodeName'},
                    {label: this.i18n('hisHtml.handlerUserName', '操作人'), field: 'handlerUserName'},
                    {label: this.i18n('hisHtml.checkStatus', '类型'), field: 'checkStatus'},
                    {label: this.i18n('hisHtml.remark', '意见'), field: 'remark'}];
                var headers = "<tr>";
                var fields = "<#list opinionList as obj><tr>";
                for (var i = 0; i < objAry.length; i++) {
                    var field = objAry[i];
                    headers += "<td>" + field.label + "</td>";
                    if (field.field == 'checkStatus') {
                        fields += "<td>${opinionMap[obj." + field.field + "]}</td>";
                    } else if (field.field == 'createTime' || field.field == 'completeTime') {
                        fields += "<td>${obj." + field.field + "?date}</td>";
                    } else {
                        fields += "<td>${obj." + field.field + "}</td>";
                    }
                }
                headers += "</tr>";
                fields += "</tr></#list>";
                f = "LODOP.ADD_PRINT_TABLE(0,0,300,100,\"<style> table,td,th {border: 1px solid black;border-style: solid;border-collapse: collapse}</style><table border='1'>" + headers + fields + "</table>\");\n";
            } else if (value == 'opinion') {
                f = 'LODOP.ADD_PRINT_HTM(0,0,300,100,"<#list opinionList as opinion>\\r\\n<div>\\r\\n  <tr><td>${opinion_index+1}.审批意见: ${opinion.remark}</td></tr>\\r\\n  <tr><td> &nbsp;&nbsp;审批人: ${opinion.handlerUserName}</td></tr>\\r\\n  <tr><td> &nbsp;&nbsp;审批时间: ${opinion.createTime?date}</td></tr>\\r\\n  <tr><td> &nbsp;&nbsp;审批类型: ${opinionMap[opinion.checkStatus]}</td></tr>\\r\\n</div>\\r\\n</#list>");\n';
            } else if (value == 'curUserId') {
                f = 'LODOP.ADD_PRINT_TEXT(0,0,278,24,"${curUser.userId}");';
            } else if (value == 'curUserName') {
                f = 'LODOP.ADD_PRINT_TEXT(0,0,278,24,"${curUser.fullName}");';
            } else if (value) {
                f = 'LODOP.ADD_PRINT_TEXT(0,0,278,24,"${' + value + '}");';
            }
            self_.scriptCode.insertContent(f);
        }
    }
}
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
</style>